<?php

namespace app\common\model;

use think\Model;
use think\Db;

class Order extends Model
{

    public function buyer()
    {
        return $this->belongsTo('User','uid','uid')->field('uid,name,tel,address');
    }

    public function shop()
    {
        return $this->belongsTo('User','shop_id','uid')->field('uid,name,tel,address');
    }

    public function detail()
    {
        return $this->hasMany('OrderDetail','order_id')
            ->field('order_id,goods_name,goods_pic,goods_num,sku_name,sku_price');
    }

    /**
     * 获取订单列表
     *
     * @param [type] $map   条件
     * @param [type] $size  每页显示记录
     * @param string $field 字段
     * @return void
     */
    public function getList($map, $size = null, $field = "*")
    {
       $list =  $this->with('shop,buyer,detail')->where($map)->field($field)->paginate($size);

       return $list;
    }

    /**
     * 获取订单详情
     *
     * @param [type] $orderid   订单id
     * @return void
     */
    public function getInfo($orderid)
    {
        $info = $this->with('shop,buyer,detail')
            ->field('id,shop_id,uid,order_money,status,is_pay,note,create_time')
            ->where('id', $orderid)
            ->find();

        return $info;
    }

    /**
     * 添加订单记录
     *
     * @return void
     */
    public function addInfo($data, $uid)
    {
        $cart = (array) $data;
        $shop_id = $cart[0]['shop_id'];
        $orderMoney = 0;
        $cartIds = [];
        $orderDetail = [];
        foreach ($cart as $k => $v) {
            if ($shop_id != $v['shop_id']) {
               return msg_code('所选商品为不同商家');
            }
            $return = model('Cart')->getInfo($v['id']);
            $orderMoney += $return['money'];
            $orderDetail[] = $return['goods_info'];
            $cartIds[] = $v['id'];
        }

        $addData = [
            'out_trade_no' => time().mt_rand(123,789),
            'shop_id' => $shop_id,
            'uid' => $uid,
            'order_money' =>  $orderMoney,
            'create_time' => time(),
            'update_time' => time(),
        ];

        $orderId = $this->insertGetId($addData);
        if ($orderId) {
            // $orderDetail = array_unique($orderDetail);
            // 添加订单详情
            foreach ($orderDetail as $v) {
                $v['order_id'] = $orderId;
                db('order_detail')->insert($v);
            }
            // 清空购物车商品
            model('Cart')->clear($cartIds);
        }
        return $orderId;
    }

    /**
     * 修改订单信息
     *
     * @param [type] $data
     * @return void
     */
    public function editInfo($data)
    {
        
    }

    /**
     * 支付订单
     *
     * @param [type] $orderid
     * @return void
     */
    public function pay($orderid, $note)
    {
        $us = model('User');
        $orderInfo = $this->where('id', $orderid)
            ->field('uid,out_trade_no,order_money,status,is_pay')->find();

        if ($orderInfo['is_pay'] == 1) {
            return msg_code('订单已支付');
        }

        $sc_coin = $us->where('uid', $orderInfo['uid'])->value('sc_coin');
        if ($orderInfo['order_money'] > $sc_coin) {
            return msg_code('账户商城币不足');
        }

        $updateData = [
            'is_pay' => 1,
            'note' => $note  
        ];

        Db::startTrans();
        try {
            $this->save($updateData, ['id' => $orderid]);
            $us->updateUserAcc(
                $orderInfo['uid'], 
                -$orderInfo['order_money'], 
                'sc_coin', 
                '商城订单：'.$orderInfo['out_trade_no'].'消费'
            );

            Db::commit();
            return msg_code('操作成功', 1);
        } catch (Exception $e) {
            Db::rollback();
            return msg_code($e->getMessage());
        }
    }

    /**
     * 确认收货
     *
     * @param [type] $orderId
     * @param [type] $note
     * @return void
     */
    public function confirm($orderId, $note = '')
    {
        $info = $this->where('id', $orderId)
            ->field('id,out_trade_no,shop_id,order_money,status,is_pay')
            ->find();

        if ($info) {
            if ($info['status'] == 1 && $info['is_pay'] == 1) {
                Db::startTrans();
                try {
                    $this->where('id', $orderId)->update(['status' => 2, 'note' => $note]);
                    model('User')->updateUserAcc(
                        $info['shop_id'], 
                        $info['order_money'], 
                        'kr_coin', 
                        '订单:'.$info['out_trade_no'].$note.'确认收货'
                    );
                    Db::commit();
                    return msg_code('操作成功！', 1);
                } catch (Exception $e) {
                    return msg_code($e->getMessage());
                }
            }
        }
        return msg_code('订单不存在！');
    }
    
    /**
     * 驳回已支付订单
     *
     * @param [type] $orderId
     * @param [type] $note
     * @return void
     */
    public function reject($orderId, $note = '')
    {
        $info = $this->where('id', $orderId)->field('id,uid,order_money,status,is_pay')->find();

        if ($info) {
            if ($info['status'] == 0 && $info['is_pay'] == 1) {
                Db::startTrans();
                try {
                    $this->where('id', $orderId)->update(['status' => -1, 'note' => $note]);
                    model('User')->updateUserAcc(
                        $info['uid'], 
                        $info['order_money'], 
                        'sc_coin', 
                        '订单取消，返还账户'
                    );
                    Db::commit();
                    return msg_code('操作成功！', 1);
                } catch (Exception $e) {
                    return msg_code($e->getMessage());
                }
            }
            return msg_code('订单状态异常，稍后重试！');
        }
        return msg_code('订单不存在！');
    }

    /**
     * 取消未支付订单
     * 
     * @param  [array] $orderid [description]
     * @return [type]          [description]
     */
    public function cancleOrder($orderid)
    {
        if (! is_array($orderid)) {
            $orderid = (array) $orderid;
        }
        // 无库存设置，无需执行库存操作
        foreach ($orderid as $v) {
           $orderInfo = $this->where('id', $v)->field('id,is_pay,status')->find();
           if ($orderInfo) {
                if ($orderInfo['status'] == 0 && $orderInfo['is_pay'] == 0) {
                    $this->where('id', $v)->delete();
                }
           }
        }
        return msg_code('操作成功', 1);
    }


}
